import ProblemFetch.Generator
import Database.getUserData
import Database.answerStorage
import Database.addPoints
import Database.getDump

import cgi
import cgitb; cgitb.enable()
import os
from mako.template import Template
from mako.lookup import TemplateLookup
import sys, traceback


nonQuestionPages = ['home', 'teacherView']
questionPages = ['algebra1', 'exponents']

def main():
	form = cgi.FieldStorage()
	env = os.environ.get

	# Get user details from DB
	loginID = env('AUTH_USER')
	alias = Database.getUserData.getUserAlias()
	position = int(Database.getUserData.getUserPosition())
	
	action = form.getfirst('action')
	if action == None:
		action = 'home'

	# Generate problem and answer
	if action in questionPages:
		(problem, answer), problemID = ProblemFetch.Generator.fetch(action)
		# Store answer with a unique problemID
		Database.answerStorage.storeAnswer(problemID, answer, action)
	else:
		problem = answer = problemID = None
	

	

	problemStatus = None

	# Get the user's answer from the html file. If they didn't put one in, it's None.
	studentAnswer = form.getfirst('studentAnswer')
	lastProblemID = form.getfirst('problemID')

	correctAnswer = None
	if studentAnswer != None and lastProblemID != 'None':
		
		answerWithProblemType = Database.answerStorage.getAnswer(int(lastProblemID))
		
		if answerWithProblemType != None and isNumber(studentAnswer):
		
			studentAnswer = float(studentAnswer)
			expectedAnswer, problemType = answerWithProblemType
			
			if studentAnswer == expectedAnswer:
				problemStatus = 'correct'
				Database.addPoints.addPoints(1)
				
			else:
				problemStatus = 'incorrect'
				correctAnswer = expectedAnswer
				
		else:
			problemStatus = 'invalid'
			
	if problemStatus != 'correct':
		if action not in nonQuestionPages:
			Database.addPoints.resetStreak()
		
		
			
	currentStreak = Database.getUserData.getCurrentStreak()
	correctAnswers = Database.getUserData.getCorrect()
	attemptedQuestions = Database.getUserData.getAttempted()
	totalPoints = Database.getUserData.getTotalPoints()
	
	assert action != None
	
	userTable = None
	isTeacherOrAdmin = (position < 2)
	if action == 'teacherView' and position < 2:
		userTable = Database.getDump.getUserTable()
	else:
		teacher = False
	
	# The data to pass the the HTML template
	templateData = {
		'userAlias':alias,
		'problem':problem,
		'currentStreak': currentStreak,
		'correctAnswers': correctAnswers,
		'attemptedQuestions': attemptedQuestions,
		'totalPoints':totalPoints,
		'problemID':problemID,
		'problemStatus': problemStatus,
		'userTable':userTable,
		'action':action,
		'correctAnswer':correctAnswer,
		'isTeacherOrAdmin':isTeacherOrAdmin
	}
	
	myLookup = TemplateLookup(directories=[''])
	template = Template(filename='Display/main.mako', lookup=myLookup)
	print template.render(**templateData)


def isNumber(inString):
	"""Is inString a number (float or int)?"""
	return inString.replace('.','').replace('-','').isdigit()


try:
	main()
except Exception as e:
	print 'Content-type: text/html\n'
	print '<h1>Oops!</h1> You broke academy :('
	print 'The admins have been notified.'
	
	f = open('errors.txt', 'a')
	traceback.print_exc(file=f)
	f.close()
